# -*- coding:utf-8 -*-
import platform
import argparse
import sys
import os
import re

__VERSION__ = 'Menuconfig v1.0.0'

DEFAULT_FN_FILE = ".config"
DEFAULT_TARGET_FILE = "autoconfig.h"

def GetDataPath(path_name):
    """Return the appropriate path for data files based on execution context"""
    if getattr(sys, 'frozen', False):
        # running in a bundle
        return(os.path.join(sys._MEIPASS, path_name))
    else:
        # running live
        return path_name

def GetTargetFile(filename):
    try:
        config = open(filename, "r")
    except:
        print("open config:%s failed" % filename)
        return None

    for line in config:
        line = line.lstrip(' ').replace('\n', '').replace('\r', '')

        if len(line) == 0: continue
        else: pass

        if line[0] == '#':
            continue
        else:
            setting = line.split('=')
            if len(setting) >= 2:
                if setting[0].startswith('CONFIG_TARGET_FILE'):
                    target_fn = re.findall(r"^.*?=(.*)$",line)[0]
                    if target_fn.startswith('"'):
                        target_fn = target_fn.replace('"', '')
                    else:
                        pass

                    if target_fn == '':
                        return None
                    else:
                        return target_fn
                else:
                    pass
            else:
                pass

    return DEFAULT_TARGET_FILE

def MkConfig(filename):
    try:
        config = open(filename, 'r')
    except Exception as e:
        print('Error message:%s' % e)
        print('open config:%s failed' % filename)
        return

    target_fn = GetTargetFile(filename)
    if target_fn == None:
        return
    else:
        pass

    auto_config = open(target_fn, 'w')
    auto_config.write('#ifndef __AUTOCONFIG_H__\n')
    auto_config.write('#define __AUTOCONFIG_H__\n\n')

    empty_line = 1

    for line in config:
        line = line.lstrip(' ').replace('\n', '').replace('\r', '')

        if len(line) == 0:
            continue
        else:
            pass

        if line[0] == '#':
            if len(line) == 1:
                if empty_line:
                    continue
                else:
                    pass

                auto_config.write('\n')
                empty_line = 1
                continue
            else:
                pass

            if line.startswith('# CONFIG_'):
                line = ' ' + line[9:]
            else:
                line = line[1:]
                auto_config.write('/*%s */\n' % line)

            empty_line = 0
        else:
            empty_line = 0
            setting = line.split('=')
            if len(setting) >= 2:
                if setting[1] == 'y':
                    auto_config.write('#define %s 1\n' % setting[0])
                else:
                    auto_config.write('#define %s %s\n' % (setting[0], re.findall(r"^.*?=(.*)$", line)[0]))
            else:
                pass

    auto_config.write('\n')
    auto_config.write('#endif\n')
    auto_config.close()

def CmdFunction(args):
    fn = DEFAULT_FN_FILE

    if platform.system() == "Windows":
        os.system("chcp 65001  > nul")
        os.system("chcp 437  > nul")
        mconf_bin = GetDataPath("kconfig-mconf.exe")
    else:
        # Fix other versions causing crashes
        os.environ['LD_LIBRARY_PATH'] = '/lib/x86_64-linux-gnu/' + os.environ.get('LD_LIBRARY_PATH')
        mconf_bin = GetDataPath("mconf")

    if not os.path.isfile(mconf_bin):
        print("%s no found!" % mconf_bin)
        return
    else:
        pass

    if args.menuconfig_g:
        MkConfig(fn)
    elif args.menuconfig_silent:
        os.system(mconf_bin + " -s Kconfig")
        MkConfig(fn)
    else:
        os.system(mconf_bin + " Kconfig")
        MkConfig(fn)


def AddParser(parser):
    parser.add_argument('--generate',
                        help='generate auto_config.h by .config.',
                        action='store_true',
                        default=False,
                        dest='menuconfig_g')

    parser.add_argument('--silent',
                        help='Silent mode,don\'t display menuconfig window.',
                        action='store_true',
                        default=False,
                        dest='menuconfig_silent')

    parser.set_defaults(func=CmdFunction)

def InitArgparse():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-v', '--version', action='version', version=__VERSION__)
    AddParser(parser)

    return parser

def main():
    parser = InitArgparse()
    args = parser.parse_args()
    args.func(args)

if __name__ == '__main__':
    main()
